<?php
namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\Log;

/**
 * 助农抢购场次管理
 *
 * @icon fa fa-calendar
 */
class Market extends Backend
{
    /**
     * 模型对应的数据表名
     * @var string
     */
    protected $table = 'agriculture_flash_sale';
    
    /**
     * 模型对应的主键名
     * @var string
     */
    protected $pk = 'id';
    
    /**
     * 默认排序字段
     * @var string
     */
    protected $orderby = 'id';
    
    /**
     * 默认排序方式
     * @var string
     */
    protected $orderway = 'desc';
    
    /**
     * 查询过滤字段
     * @var array
     */
    protected $searchFields = 'title,description';
    
    /**
     * 初始化方法
     */
    public function _initialize()
    {
        parent::_initialize();
    }
    
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter = $filter ? $filter : [];
            $op = $this->request->get("op", '');
            $op = (array)json_decode($op, true);
            $op = $op ? $op : [];
            
            $where = [];
            $filterArr = [];
            if ($filter && $op) {
                foreach ($filter as $k => $v) {
                    if (isset($op[$k])) {
                        $filterArr[] = [$k, $op[$k], $v];
                    }
                }
            }
            
            // 处理状态筛选
            $status = $this->request->get('status', '');
            if ($status !== '') {
                $where['status'] = $status;
            }
            
            $list = Db::name($this->table)
                ->where($where)
                ->where($filterArr)
                ->order($this->orderby, $this->orderway)
                ->paginate($this->request->get('limit', 10));
                
            $result = ['total' => $list->total(), 'rows' => $list->items()];
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                $start_time = strtotime($params['start_time']);
                $end_time = strtotime($params['end_time']);
                if ($start_time >= $end_time) {
                    $this->error('开始时间不能大于等于结束时间');
                }
                
                if (!isset($params['title']) || empty($params['title'])) {
                    $params['title'] = date('Y年m月d日抢购', $start_time);
                }
                if (!isset($params['description'])) {
                    $params['description'] = '';
                }
                if (!isset($params['description'])) {
                    $params['description'] = '';
                }
                $params['start_time'] = $start_time;
                $params['end_time'] = $end_time;
                $params['status'] = 0;
                $params['sort'] = 0;
                $params['createtime'] = time();
                $params['updatetime'] = time();
                
                // 获取抢购商品数据
                $flashProducts = $this->request->post('flash_products', '');
                $flashProductsArray = $flashProducts ? json_decode($flashProducts, true) : [];
                
                $result = false;
                Db::startTrans();
                try {
                    // 插入抢购场次
                    $result = Db::name($this->table)->insertGetId($params);
                    
                    // 处理抢购商品数据
                    if ($result !== false && !empty($flashProductsArray)) {
                        $flashSaleId = $result;
                        $flashProductsData = [];
                        foreach ($flashProductsArray as $product) {
                            $flashProductsData[] = [
                                'flash_sale_id' => $flashSaleId,
                                'product_id' => $product['product_id'],
                                'product_sku_id' => $product['product_sku_id'],
                                'original_price' => 0, // 这里应该从商品表获取原价
                                'flash_price' => $product['flash_price'],
                                'limit_num' => $product['limit_num'],
                                'sales' => 0,
                                'status' => $product['status'],
                                'createtime' => time(),
                                'updatetime' => time()
                            ];
                        }
                        
                        if (!empty($flashProductsData)) {
                            Db::name('agriculture_flash_sale_product')->insertAll($flashProductsData);
                        }
                    }
                    
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = Db::name($this->table)->where('id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                $start_time = strtotime($params['start_time']);
                $end_time = strtotime($params['end_time']);
                if ($start_time >= $end_time) {
                    $this->error('开始时间不能大于等于结束时间');
                }
                
                if (!isset($params['title']) || empty($params['title'])) {
                    $params['title'] = date('Y年m月d日抢购', $start_time);
                }
                $params['start_time'] = $start_time;
                $params['end_time'] = $end_time;
                $params['updatetime'] = time();
                
                // 获取抢购商品数据
                $flashProducts = $this->request->post('flash_products', '');
                $flashProductsArray = $flashProducts ? json_decode($flashProducts, true) : [];
                
                $result = false;
                Db::startTrans();
                try {
                    // 更新抢购场次信息
                    $result = Db::name($this->table)->where('id', $ids)->update($params);
                    
                    // 处理抢购商品数据
                    if ($result !== false && !empty($flashProductsArray)) {
                        // 先删除原有的抢购商品关联
                        Db::name('agriculture_flash_sale_product')->where('flash_sale_id', $ids)->delete();
                        
                        // 添加新的抢购商品关联
                        $flashProductsData = [];
                        foreach ($flashProductsArray as $product) {
                            $flashProductsData[] = [
                                'flash_sale_id' => $ids,
                                'product_id' => $product['product_id'],
                                'product_sku_id' => $product['product_sku_id'],
                                'original_price' => 0, // 这里应该从商品表获取原价
                                'flash_price' => $product['flash_price'],
                                'limit_num' => $product['limit_num'],
                                'sales' => 0,
                                'status' => $product['status'],
                                'createtime' => time(),
                                'updatetime' => time()
                            ];
                        }
                        
                        if (!empty($flashProductsData)) {
                            Db::name('agriculture_flash_sale_product')->insertAll($flashProductsData);
                        }
                    }
                    
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 格式化时间显示
        $row['start_time'] = date('Y-m-d H:i:s', $row['start_time']);
        $row['end_time'] = date('Y-m-d H:i:s', $row['end_time']);
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->pk;
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = Db::name($this->table)->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    // 删除抢购场次
                    $count += Db::name($this->table)->where('id', $v['id'])->delete();
                    // 删除关联的抢购商品
                    Db::name('agriculture_flash_sale_product')->where('flash_sale_id', $v['id'])->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    /**
     * 获取特定商品在特定抢购场次中的规格信息
     */
    public function getFlashProductSpecs()
    {
        $flash_sale_id = $this->request->get('flash_sale_id');
        $product_id = $this->request->get('product_id');

        // 记录请求参数
        Log::write('getFlashProductSpecs请求参数 - flash_sale_id: ' . $flash_sale_id . ', product_id: ' . $product_id, 'info');
        
        if (empty($product_id)) {
            $this->error(__('商品ID不能为空'));
        }
        
        if (empty($flash_sale_id)) {
            $this->error(__('抢购场次ID不能为空'));
        }
        
        // 获取商品基本信息
        $product = Db::name('product')
            ->where('id', $product_id)
            ->field('id, name, merchant_id, price, stock')
            ->find();

        Log::write('查询商品基本信息结果: ' . json_encode($product), 'info');
        
        if (!$product) {
            $this->error(__('商品不存在'));
        }
        
        // 获取商品规格信息（只需要规格名称，价格由用户手动输入）
        $specs = Db::name('product_sku')
            ->where('product_id', $product_id)
            ->field('id, sku_name as spec_name, price, stock')
            ->select();

        // 为每个规格添加默认的抢购价格和限购数量（供前端显示，用户可以修改）
        foreach ($specs as &$spec) {
            $spec['flash_price'] = $product['price']; // 默认抢购价格为商品原价
            $spec['limit_num'] = 0; // 默认限购数量为0，用户需要手动设置
        }
        
        // 记录返回数据
        Log::write('返回的商品规格数据: ' . json_encode($specs), 'info');

        return json(['code' => 1, 'msg' => '获取成功', 'data' => ['product' => $product,'specs' => $specs]]);
    }
    
    /**
     * 获取抢购商品
     */
    public function getFlashProducts()
    {
        $flash_sale_id = $this->request->get('flash_sale_id');
        
        // 记录请求参数
        Log::write('getFlashProducts请求参数 - flash_sale_id: ' . $flash_sale_id, 'info');
        
        // 获取抢购商品数据
        $products = Db::name('agriculture_flash_sale_product')
            ->where('flash_sale_id', $flash_sale_id)
            ->select();
        // 记录查询结果
        Log::write('查询到的抢购商品数据: ' . json_encode($products), 'info');
        
        // 补充商品信息
        foreach ($products as &$product) {
            
            // 获取商品基本信息
            $productInfo = Db::name('product')
                ->where('id', $product['product_id'])
                ->field('id, name, merchant_id')
                ->find();
            
            if ($productInfo) {
                $product['product_name'] = $productInfo['name'];
                
                // 获取商家信息
                $merchant = Db::name('merchant_audit')
                    ->where('merchant_id', $productInfo['merchant_id'])
                    ->field('id, store_name')
                    ->find();
                $product['merchant_name'] = $merchant['store_name'];

            } else {
                $product['product_name'] = '商品ID: ' . $product['product_id'];
                $product['merchant_name'] = '未知商家';
            }
        }
        
        // 记录返回数据
        Log::write('返回的抢购商品数据: ' . json_encode($products), 'info');
            
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $products]);
    }

    /**
     * 商品选择弹窗
     */
    public function select()
    {
        // 获取商品列表 - 只显示审核通过的商品
        $list = Db::name('product')
            ->where('audit_status', 1)
            ->field('id, name, price, main_image, stock')
            ->order('id desc')
            ->paginate(10);

        $this->view->assign("list", $list);
        return $this->view->fetch();
    }

    /**
     * 获取商品规格信息
     */
    public function getProductSpecs()
    {
        // 添加调试日志
        Log::write('getProductSpecs方法被调用', 'info');
        
        $product_id = $this->request->get('product_id');
        Log::write('接收到的商品ID: ' . $product_id, 'info');
        Log::write('获取商品规格信息，商品ID: ' . $product_id, 'info');
        
        if (!$product_id) {
            Log::write('商品ID为空', 'error');
            $this->error(__('商品ID不能为空'));
        }
        
        // 获取商品基本信息
        $product = Db::name('product')->where('id', $product_id)->find();
        Log::write('查询到的商品信息: ' . json_encode($product), 'info');
        
        if (!$product) {
            Log::write('商品不存在，ID: ' . $product_id, 'error');
            $this->error(__('商品不存在'));
        }
        
        // 获取商品规格信息
        try {
            // 尝试从product_sku表获取数据
            Log::write('尝试从product_sku表获取规格数据', 'info');
            $specs = Db::name('product_sku')
                ->where('product_id', $product_id)
                ->field('id, sku_name as spec_name, price, stock')
                ->select();
                
            Log::write('product_sku表查询结果: ' . json_encode($specs), 'info');
                
            // 如果product_sku表没有数据，尝试从product_spec表获取
            if (empty($specs)) {
                Log::write('product_sku表无数据，尝试从product_spec表获取', 'info');
                $specs = Db::name('product_spec')
                    ->where('product_id', $product_id)
                    ->field('id, spec_name, price, stock')
                    ->select();
                    
                Log::write('product_spec表查询结果: ' . json_encode($specs), 'info');
            }
        } catch (\Exception $e) {
            Log::write('查询商品规格出错: ' . $e->getMessage(), 'error');
            // 出错时返回空数组，后续会创建默认规格
            $specs = [];
        }
        
        Log::write('查询到的规格信息: ' . json_encode($specs), 'info');
        
        // 如果没有规格，创建默认规格
        if (empty($specs)) {
            Log::write('未找到商品规格，创建默认规格', 'info');
            
            // 确保product中有price和stock字段
            $defaultPrice = isset($product['price']) && is_numeric($product['price']) ? $product['price'] : 0;
            $defaultStock = isset($product['stock']) && is_numeric($product['stock']) ? $product['stock'] : 999;
            
            Log::write('默认价格: ' . $defaultPrice . ', 默认库存: ' . $defaultStock, 'info');
            
            $specs = [[
                'id' => 0,
                'spec_name' => '默认规格',
                'price' => $defaultPrice,
                'stock' => $defaultStock
            ]];
            Log::write('创建的默认规格: ' . json_encode($specs), 'info');
        }
        
        // 确保每个规格都有必要的字段
        foreach ($specs as &$spec) {
            if (!isset($spec['id'])) $spec['id'] = 0;
            if (!isset($spec['spec_name'])) $spec['spec_name'] = '默认规格';
            if (!isset($spec['price']) || !is_numeric($spec['price'])) $spec['price'] = isset($product['price']) ? $product['price'] : 0;
            if (!isset($spec['stock']) || !is_numeric($spec['stock'])) $spec['stock'] = isset($product['stock']) ? $product['stock'] : 999;
        }
        unset($spec); // 解除引用
        
        $result = [
            'product' => $product,
            'specs' => $specs
        ];
        
        Log::write('返回结果: ' . json_encode($result), 'info');
        
        $this->success(__('获取成功'), null, $result);
    }

    /**
     * 商品添加弹窗
     */
    public function product_add()
    {
        if ($this->request->isPost()) {
            // 直接从POST中获取参数，不使用row数组
            $product_id = $this->request->post('product_id/d', 0);
            $specs = $this->request->post('specs/a', []);
            // 如果specs是JSON字符串，则解析为数组
            if (!empty($specs) && is_string($specs)) {
                $specs = json_decode($specs, true);
                Log::write('解析JSON后的specs: ' . json_encode($specs), 'info');
            }
            $flash_sale_id = $this->request->post('flash_sale_id/d', 0);
           
            // 验证必填字段
            if (empty($product_id)) {
                $this->error(__('商品ID不能为空'));
            }
            if (!is_array($specs) || empty($specs)) {
                $this->error(__('规格数据不能为空'));
            }
            
            if (empty($flash_sale_id)) {
                $this->error(__('抢购场次ID不能为空'));
            }
            
            // 验证规格数据
            foreach ($specs as $index => $spec) {
                if (!is_array($spec)) {
                    Log::write('规格数据项不是数组，索引: ' . $index . ', 类型: ' . gettype($spec), 'error');
                    $this->error(__('规格数据格式错误'));
                }
                
                if (!isset($spec['spec_id']) || !is_numeric($spec['spec_id'])) {
                    Log::write('规格ID无效，索引: ' . $index . ', spec_id: ' . var_export($spec['spec_id'] ?? null, true), 'error');
                    $this->error(__('规格ID无效'));
                }
                
                if (!isset($spec['flash_price']) || !is_numeric($spec['flash_price']) || $spec['flash_price'] < 0) {
                    Log::write('抢购价格无效，索引: ' . $index . ', flash_price: ' . var_export($spec['flash_price'] ?? null, true), 'error');
                    $this->error(__('抢购价格必须为有效的非负数'));
                }
                
                if (isset($spec['limit_num']) && !is_numeric($spec['limit_num'])) {
                    Log::write('限购数量无效，索引: ' . $index . ', limit_num: ' . var_export($spec['limit_num'], true), 'error');
                    $this->error(__('限购数量必须为有效数字'));
                }
            }
            
            // 检查商品是否已存在于该抢购场次中
            $existingProduct = Db::name('agriculture_flash_sale_product')
                ->where('flash_sale_id', $flash_sale_id)
                ->where('product_id', $product_id)
                ->find();
            
            if ($existingProduct) {
                $this->error(__('该商品已存在于当前抢购场次中'));
            }
            
            // 获取商品信息
            $product = Db::name('product')->where('id', $product_id)->find();
            if (!$product) {
                $this->error(__('商品不存在'));
            }
            
            Db::startTrans();
            try {
                // 保存每个规格的抢购商品数据
                foreach ($specs as $spec) {
                    $flashProductData = [
                        'flash_sale_id' => intval($flash_sale_id),
                        'product_id' => intval($product_id),
                        'product_sku_id' => intval($spec['spec_id']),
                        'flash_price' => floatval($spec['flash_price']),
                        'original_price' => floatval($spec['flash_price']), // 暂时使用抢购价作为原价
                        'stock' => intval($spec['limit_num']) ?: 0,
                        'limit_num' => intval($spec['limit_num']) ?: 0,
                        'sales' => 0,
                        'status' => 1,
                        'createtime' => time(),
                        'updatetime' => time()
                    ];
                    
                    Db::name('agriculture_flash_sale_product')->insert($flashProductData);
                }
                
                Db::commit();
                
                // 获取商品完整信息
                $productInfo = Db::name('product')
                    ->where('id', $product_id)
                    ->field('id, name, merchant_id')
                    ->find();
                
                // 返回商品数据
                $result = [
                    'product_id' => intval($product_id),
                    'product_name' => $productInfo ? $productInfo['name'] : '商品ID: ' . $product_id,
                    'specs' => $specs,
                    'flash_sale_id' => $flash_sale_id,
                    'status' => 1 // 新添加的商品默认为在售状态
                ];
                
                Log::write('添加成功，返回数据: ' . json_encode($result), 'info');
                $this->success(__('添加成功'), null, $result);
                
            } catch (Exception $e) {
                Db::rollback();
                $this->error(__('保存失败：') . $e->getMessage());
            }
        }
        
        // GET请求显示表单
        $flash_sale_id = $this->request->get('flash_sale_id');
        
        $this->view->assign("flash_sale_id", $flash_sale_id);
        return $this->view->fetch('product_add'); // 使用product_add模板
    }
    
    /**
     * 商品编辑弹窗
     */
    public function product_edit()
    {
        if ($this->request->isPost()) {
            try {
                // 获取POST参数
                $postData = $this->request->post();
                // 验证必要参数
                if (!isset($postData['product_id']) || empty($postData['product_id'])) {
                    $this->error('商品ID不能为空');
                }
                
                if (!isset($postData['flash_sale_id']) || empty($postData['flash_sale_id'])) {
                    $this->error('抢购场次ID不能为空');
                }
                
                if (!isset($postData['specs']) || empty($postData['specs'])) {
                    $this->error('规格数据不能为空');
                }
                
                $product_id = intval($postData['product_id']);
                $flash_sale_id = intval($postData['flash_sale_id']);
                $specs = $postData['specs'];
                
                // 处理specs数据
                if (is_string($specs)) {
                    $specs = json_decode($specs, true);
                    if (json_last_error() !== JSON_ERROR_NONE) {
                        $this->error('规格数据格式错误');
                    }
                }
                
                if (!is_array($specs) || empty($specs)) {
                    $this->error('规格数据格式错误');
                }
                
                // 验证商品是否存在
                $product = Db::name('product')->where('id', $product_id)->find();
                if (!$product) {
                    $this->error('商品不存在');
                }
                
                // 开始事务
                Db::startTrans();
                
                // 处理每个规格
                foreach ($specs as $spec) {
                    if (!isset($spec['spec_id']) || !isset($spec['flash_price'])) {
                        Db::rollback();
                        $this->error('规格数据不完整');
                    }
                    
                    $flashProductData = [
                        'flash_sale_id' => $flash_sale_id,
                        'product_id' => $product_id,
                        'product_sku_id' => intval($spec['spec_id']),
                        'flash_price' => floatval($spec['flash_price']),
                        'original_price' => floatval($spec['flash_price']),
                        'stock' => isset($spec['limit_num']) ? intval($spec['limit_num']) : 0,
                        'limit_num' => isset($spec['limit_num']) ? intval($spec['limit_num']) : 0,
                        'status' => 1,
                        'updatetime' => time()
                    ];
                    
                    // 如果有ID则更新，否则新增
                    if (isset($spec['id']) && intval($spec['id']) > 0) {
                        $existingRecord = Db::name('agriculture_flash_sale_product')
                            ->where('id', intval($spec['id']))
                            ->find();
                        
                        if ($existingRecord) {
                            $flashProductData['sales'] = $existingRecord['sales'];
                            $flashProductData['createtime'] = $existingRecord['createtime'];
                            
                            Db::name('agriculture_flash_sale_product')
                                ->where('id', intval($spec['id']))
                                ->update($flashProductData);
                        }
                    } else {
                        
                        $flashProductData['createtime'] = time();
                        $flashProductData['sales'] = 0;
                        
                        Db::name('agriculture_flash_sale_product')->insert($flashProductData);
                    }
                }
                
                Db::commit();
                
                // 获取商品信息
                $productInfo = Db::name('product')
                    ->where('id', $product_id)
                    ->field('id, name, merchant_id')
                    ->find();
                
                $merchantName = '未知商家';
                if ($productInfo && !empty($productInfo['merchant_id'])) {
                    $merchant = Db::name('merchant_audit')
                        ->where('id', $productInfo['merchant_id'])
                        ->field('id, store_name')
                        ->find();
                    
                    if ($merchant) {
                        $merchantName = $merchant['store_name'];
                    }
                }
                
                $result = [
                    'product_id' => $product_id,
                    'product_name' => $productInfo ? $productInfo['name'] : '商品ID: ' . $product_id,
                    'merchant_name' => $merchantName,
                    'specs' => $specs,
                    'flash_sale_id' => $flash_sale_id,
                    'status' => 1
                ];
                
                $this->success('编辑成功', null, $result);
                
            } catch (Exception $e) {
                Db::rollback();
                $this->error('保存失败：' . $e->getMessage());
            }
        }
        
        return $this->view->fetch();
    }
    
    /**
     * 获取抢购商品配置数据（用于编辑）
     * 查询 fa_agriculture_flash_sale_product 表的数据
     */
    public function getFlashSaleProducts()
    {
        $flash_sale_id = $this->request->get('flash_sale_id/d', 0);
        $product_id = $this->request->get('product_id/d', 0);
        
        Log::write('getFlashSaleProducts 请求参数 - flash_sale_id: ' . $flash_sale_id . ', product_id: ' . $product_id, 'info');
        
        if (empty($flash_sale_id)) {
            $this->error(__('抢购场次ID不能为空'));
        }
        
        if (empty($product_id)) {
            $this->error(__('商品ID不能为空'));
        }
        
        try {
            // 查询抢购商品配置数据
            $flashProducts = Db::name('agriculture_flash_sale_product')
                ->where('flash_sale_id', $flash_sale_id)
                ->where('product_id', $product_id)
                ->field('id, flash_sale_id, product_id, product_sku_id, flash_price, original_price, stock, limit_num, sales, status, createtime, updatetime')
                ->select();
            
            Log::write('查询到的抢购商品配置数据: ' . json_encode($flashProducts), 'info');
            
            if (empty($flashProducts)) {
                $this->error(__('未找到该商品的抢购配置数据'));
            }
            
            // 获取商品规格信息，补充规格名称
            $specs = [];
            foreach ($flashProducts as $flashProduct) {
                
                $spec_id = $flashProduct['product_sku_id'];
                
                // 获取规格信息
                $specInfo = Db::name('product_sku')
                    ->where('id', $spec_id)
                    ->field('id, sku_name as spec_name, price, stock')
                    ->find();
                
                if ($specInfo) {
                    $specs[] = [
                        'id' => $flashProduct['id'], // 抢购商品配置ID
                        'spec_id' => $spec_id,
                        'spec_name' => $specInfo['spec_name'],
                        'price' => $specInfo['price'], // 原价
                        'stock' => $specInfo['stock'], // 商品库存
                        'flash_price' => $flashProduct['flash_price'], // 抢购价
                        'original_price' => $flashProduct['original_price'], // 抢购配置中的原价
                        'flash_stock' => $flashProduct['stock'], // 抢购库存
                        'limit_num' => $flashProduct['limit_num'], // 限购数量
                        'sales' => $flashProduct['sales'], // 已售数量
                        'status' => $flashProduct['status'], // 状态
                        'createtime' => $flashProduct['createtime'],
                        'updatetime' => $flashProduct['updatetime']
                    ];
                } 
            }
            
            // 获取商品基本信息
            $productInfo = Db::name('product')
                ->where('id', $product_id)
                ->field('id, name, merchant_id')
                ->find();
            
            $result = [
                'product_id' => $product_id,
                'product_name' => $productInfo ? $productInfo['name'] : '商品ID: ' . $product_id,
                'flash_sale_id' => $flash_sale_id,
                'specs' => $specs
            ];
            
            Log::write('getFlashSaleProducts 返回数据: ' . json_encode($result), 'info');

            //  return json(['code' => 1, 'msg' => '获取成功', 'data' => $result]);

            $this->success(__('获取成功'), null, $result);
            
        } catch (Exception $e) {
            Log::write('getFlashSaleProducts 异常: ' . $e->getMessage(), 'error');
            $this->error(__('获取失败：') . $e->getMessage());
        }
    }
    
    /**
     * 下架商品
     * 将抢购商品状态设置为0
     */
    public function product_offline()
    {
        if ($this->request->isPost()) {
            try {
                $postData = $this->request->post();
                
                // 验证必要参数
                if (!isset($postData['product_id']) || empty($postData['product_id'])) {
                    $this->error('商品ID不能为空');
                }
                
                if (!isset($postData['flash_sale_id']) || empty($postData['flash_sale_id'])) {
                    $this->error('抢购场次ID不能为空');
                }
                
                $product_id = intval($postData['product_id']);
                $flash_sale_id = intval($postData['flash_sale_id']);
                
                // 验证商品是否存在
                $product = Db::name('product')->where('id', $product_id)->find();
                if (!$product) {
                    $this->error('商品不存在');
                }
                
                // 查询该商品的抢购配置
                $flashProducts = Db::name('agriculture_flash_sale_product')
                    ->where('flash_sale_id', $flash_sale_id)
                    ->where('product_id', $product_id)
                    ->select();
                
                if (empty($flashProducts)) {
                    $this->error('未找到该商品的抢购配置');
                }
                
                // 开始事务
                Db::startTrans();
                
                try {
                    // 将该商品的所有规格状态设置为0（下架）
                    $result = Db::name('agriculture_flash_sale_product')
                        ->where('flash_sale_id', $flash_sale_id)
                        ->where('product_id', $product_id)
                        ->update([
                            'status' => 0,
                            'updatetime' => time()
                        ]);
                    
                    if ($result === false) {
                        throw new Exception('下架操作失败');
                    }
                    
                    Db::commit();
                    
                    // 获取商品信息
                    $productInfo = Db::name('product')
                        ->where('id', $product_id)
                        ->field('id, name, merchant_id')
                        ->find();
                    
                    $merchantName = '未知商家';
                    if ($productInfo && !empty($productInfo['merchant_id'])) {
                        $merchant = Db::name('merchant_audit')
                            ->where('id', $productInfo['merchant_id'])
                            ->field('id, store_name')
                            ->find();
                        
                        if ($merchant) {
                            $merchantName = $merchant['store_name'];
                        }
                    }
                    
                    $resultData = [
                        'product_id' => $product_id,
                        'product_name' => $productInfo ? $productInfo['name'] : '商品ID: ' . $product_id,
                        'merchant_name' => $merchantName,
                        'flash_sale_id' => $flash_sale_id,
                        'status' => 0
                    ];
                    
                    $this->success('下架成功', null, $resultData);
                    
                } catch (Exception $e) {
                    Db::rollback();
                    throw $e;
                }
                
            } catch (Exception $e) {
                $this->error('下架失败：' . $e->getMessage());
            }
        }
        
        $this->error('请求方式错误');
    }
    
    /**
     * 保存抢购商品配置
     * 计算抢购限制数量总数并保存
     */
    public function product_save()
    {
        if ($this->request->isPost()) {
            try {
                // 获取POST参数
                $postData = $this->request->post();
                
                // 验证必要参数
                if (!isset($postData['product_id']) || empty($postData['product_id'])) {
                    $this->error('商品ID不能为空');
                }
                
                if (!isset($postData['flash_sale_id']) || empty($postData['flash_sale_id'])) {
                    $this->error('抢购场次ID不能为空');
                }
                
                if (!isset($postData['specs']) || empty($postData['specs'])) {
                    $this->error('规格数据不能为空');
                }
                
                $product_id = intval($postData['product_id']);
                $flash_sale_id = intval($postData['flash_sale_id']);
                $specs = $postData['specs'];
                
                // 处理specs数据
                if (is_string($specs)) {
                    $specs = json_decode($specs, true);
                    if (json_last_error() !== JSON_ERROR_NONE) {
                        $this->error('规格数据格式错误');
                    }
                }
                
                if (!is_array($specs) || empty($specs)) {
                    $this->error('规格数据格式错误');
                }
                
                // 验证商品是否存在
                $product = Db::name('product')->where('id', $product_id)->find();
                if (!$product) {
                    $this->error('商品不存在');
                }
                
                // 计算抢购限制数量总数
                $totalLimitNum = 0;
                $totalStock = 0;
                $minPrice = null;
                
                foreach ($specs as $spec) {
                    if (!isset($spec['spec_id']) || !isset($spec['flash_price'])) {
                        $this->error('规格数据不完整');
                    }
                    
                    $limitNum = isset($spec['limit_num']) ? intval($spec['limit_num']) : 0;
                    $flashPrice = floatval($spec['flash_price']);
                    
                    $totalLimitNum += $limitNum;
                    $totalStock += $limitNum; // 库存等于限制数量
                    
                    // 计算最低价格
                    if ($minPrice === null || $flashPrice < $minPrice) {
                        $minPrice = $flashPrice;
                    }
                }
                
                // 开始事务
                Db::startTrans();
                
                try {
                    // 处理每个规格
                    foreach ($specs as $spec) {
                        $flashProductData = [
                            'flash_sale_id' => $flash_sale_id,
                            'product_id' => $product_id,
                            'product_sku_id' => intval($spec['spec_id']),
                            'flash_price' => floatval($spec['flash_price']),
                            'original_price' => floatval($spec['flash_price']),
                            'stock' => isset($spec['limit_num']) ? intval($spec['limit_num']) : 0,
                            'limit_num' => isset($spec['limit_num']) ? intval($spec['limit_num']) : 0,
                            'status' => 1,
                            'updatetime' => time()
                        ];
                        
                        // 如果有ID则更新，否则新增
                        if (isset($spec['id']) && intval($spec['id']) > 0) {
                            $existingRecord = Db::name('agriculture_flash_sale_product')
                                ->where('id', intval($spec['id']))
                                ->find();
                            
                            if ($existingRecord) {
                                $flashProductData['sales'] = $existingRecord['sales'];
                                $flashProductData['createtime'] = $existingRecord['createtime'];
                                
                                Db::name('agriculture_flash_sale_product')
                                    ->where('id', intval($spec['id']))
                                    ->update($flashProductData);
                            }
                        } else {
                            $flashProductData['createtime'] = time();
                            $flashProductData['sales'] = 0;
                            
                            Db::name('agriculture_flash_sale_product')->insert($flashProductData);
                        }
                    }
                    
                    Db::commit();
                    
                    // 获取商品信息
                    $productInfo = Db::name('product')
                        ->where('id', $product_id)
                        ->field('id, name, merchant_id')
                        ->find();
                    
                    $merchantName = '未知商家';
                    if ($productInfo && !empty($productInfo['merchant_id'])) {
                        $merchant = Db::name('merchant_audit')
                            ->where('id', $productInfo['merchant_id'])
                            ->field('id, store_name')
                            ->find();
                        
                        if ($merchant) {
                            $merchantName = $merchant['store_name'];
                        }
                    }
                    
                    // 返回保存结果和统计数据
                    $result = [
                        'product_id' => $product_id,
                        'product_name' => $productInfo ? $productInfo['name'] : '商品ID: ' . $product_id,
                        'merchant_name' => $merchantName,
                        'specs' => $specs,
                        'flash_sale_id' => $flash_sale_id,
                        'status' => 1,
                        'total_limit_num' => $totalLimitNum, // 抢购限制数量总数
                        'total_stock' => $totalStock, // 总库存
                        'min_price' => $minPrice, // 最低价格
                        'spec_count' => count($specs), // 规格数量
                        'save_time' => date('Y-m-d H:i:s')
                    ];
                    
                    $this->success('保存成功', null, $result);
                    
                } catch (Exception $e) {
                    Db::rollback();
                    throw $e;
                }
                
            } catch (Exception $e) {
                $this->error('保存失败：' . $e->getMessage());
            }
        }
        
        $this->error('请求方式错误');
    }

    /**
     * 获取历史商品列表
     * 查询status=0的已下架商品
     */
    public function getHistoryProducts()
    {
        try {
            $flash_sale_id = $this->request->get('flash_sale_id/d', 0);
            $page = $this->request->get('page/d', 1);
            $limit = $this->request->get('limit/d', 10);
            
            if (empty($flash_sale_id)) {
                $this->error('抢购场次ID不能为空');
            }
            
            // 查询已下架的商品（status=0）
            $where = [
                'flash_sale_id' => $flash_sale_id,
                'status' => 0
            ];
            
            // 分组查询，按product_id分组，避免重复显示同一商品的多个规格
            $flashProducts = Db::name('agriculture_flash_sale_product')
                ->where($where)
                ->field('product_id, flash_sale_id, MAX(updatetime) as updatetime, COUNT(*) as spec_count')
                ->group('product_id, flash_sale_id')
                ->order('updatetime', 'desc')
                ->page($page, $limit)
                ->select();
            
            // 获取总数
            $total = Db::name('agriculture_flash_sale_product')
                ->where($where)
                ->group('product_id')
                ->count();
            
            $result = [];
            foreach ($flashProducts as $flashProduct) {
                $product_id = $flashProduct['product_id'];
                
                // 获取商品基本信息
                $productInfo = Db::name('product')
                    ->where('id', $product_id)
                    ->field('id, name, merchant_id')
                    ->find();

                // 获取商家信息
                $merchantName = '未知商家';
                if ($productInfo && !empty($productInfo['merchant_id'])) {
                    $merchant = Db::name('merchant_audit')
                        ->where('merchant_id', $productInfo['merchant_id'])
                        ->field('id, store_name')
                        ->find();
                    
                    if ($merchant) {
                        $merchantName = $merchant['store_name'];
                    }
                }
                
                // 获取该商品的抢购数据统计
                $productStats = Db::name('agriculture_flash_sale_product')
                    ->where('flash_sale_id', $flash_sale_id)
                    ->where('product_id', $product_id)
                    ->where('status', 0)
                    ->field('SUM(sales) as total_sales, SUM(stock) as total_stock, MIN(flash_price) as min_price')
                    ->find();
                
                $result[] = [
                    'product_id' => $product_id,
                    'product_name' => $productInfo ? $productInfo['name'] : '商品ID: ' . $product_id,
                    'merchant_name' => $merchantName,
                    'spec_count' => $flashProduct['spec_count'], // 规格数量
                    'total_sales' => $productStats['total_sales'] ?: 0, // 总销量
                    'total_stock' => $productStats['total_stock'] ?: 0, // 总库存
                    'min_price' => $productStats['min_price'] ?: 0, // 最低价格
                    'flash_sale_id' => $flash_sale_id,
                    'offline_time' => date('Y-m-d H:i:s', $flashProduct['updatetime']), // 下架时间
                    'status' => 0
                ];
            }
            
            $responseData = [
                'total' => $total,
                'page' => $page,
                'limit' => $limit,
                'list' => $result
            ];
            
            $this->success('获取成功', null, $responseData);
            
        } catch (Exception $e) {
            $this->error('获取失败：' . $e->getMessage());
        }
    }
}